<?php

namespace App\Http\Controllers\Api;

use App\Domain\Lendhist\Model\Lendhist;
use App\Domain\Lendhist\Service\LendhistService;
use App\Domain\Lendlist\Service\LendlistService;
use App\Http\Service\ServiceBook;
use App\Util\Result;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Service\ServiceShare;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;

class ShareController extends Controller
{
    use ServiceShare;
    use ServiceBook;

    protected $lendLisService = null;
    protected $lendHisService = null;

    public function __construct(Request $request,LendlistService $lendlistService,LendhistService $lendhistService){
        $this->request = $request;
        $this->lendLisService=$lendlistService;
        $this->lendHisService=$lendhistService;

    }

    /**
     * 增加读者
     */
    public function addReader() {
        if ($this->request->isMethod('post')) {
            $data['uid'] = $this->request->input('uid');
            $data['created_at'] = time();
            $res = $this->addReaders($data);
            return $res->getResult();
        } else {
            return Result::failure()->settype(1)->getResult();
        }
    }

    /**
     * 最近的书柜
     */
    public function nearest() {
        if ($this->request->isMethod('post')) {
            $lat = $this->request->input('lat');
            $lon = $this->request->input('lon');
            $res = DB::table('shelves as a')
                ->leftjoin('doors as b','b.sid','=','a.id')
                ->leftjoin('booksindoor as c','c.DoorID','=','b.code')
                ->groupBy('a.number','a.type','a.name','a.address','a.lati','a.longi','a.id')
                ->select(DB::raw('a.id,a.number,a.type,a.name,a.address,a.lati,a.longi,count(c.id) as count,ROUND(6378.138*2*ASIN(SQRT(POW(SIN(('.$lat.'*PI()/180-lati*PI()/180)/2),2)+COS('.$lat.'*PI()/180)*COS(lati*PI()/180)*POW(SIN(('.$lon.'*PI()/180-longi*PI()/180)/2),2)))*1000)
                   AS juli'))->orderby('juli','asc')
                ->limit(1)
                ->first();
            return Result::success()->setData($res)->setType(0)->getResult();
        } else {
            return Result::failure()->settype(1)->getResult();
        }
    }

    /**
     * 地图柜子列表
     */
    public function shelfList() {
        if ($this->request->isMethod('post')) {
            $data['up'] = $this->request->input('up');
            $data['down'] = $this->request->input('down');
            $data['left'] = $this->request->input('left');
            $data['right'] = $this->request->input('right');
            $res = $this->shelfLists($data);
            return $res->getResult();
        } else {
            return Result::failure()->settype(1)->getResult();
        }
    }

    /**
     * 图书列表
     */
    public function bookList() {
        if ($this->request->isMethod('post')) {
            $sid = $this->request->input('sid');
            $p = $this->request->input('p');
            $res = $this->shelf($sid,$p);
            return $res->getResult();
        } else {
            return Result::failure()->settype(1)->getResult();
        }
    }

    /**
     * 图书详情
     */
    public function bookDetail() {
        if ($this->request->isMethod('post')) {
            $bid = $this->request->input('bid');
            $res = $this->book($bid);
            return $res->getResult();
        } else {
            return Result::failure()->settype(1)->getResult();
        }
    }

    /**
     * 买书
     */
    public function buyBook() {
        if ($this->request->isMethod('post')) {
            $bid = $this->request->input('bid');
            $uid = $this->request->input('uid');
            DB::beginTransaction();
            //删除借书记录
            $this->lendLisService->delListByBookid($bid);
            $this->lendHisService->updateLendHistByBookId($bid,'',Lendhist::STATUS_2);
            $res2 = DB::table('Items as a')
                ->where('a.SerialNo',$bid)
                ->update(['a.LTStatus'=>6]);
            if (empty($res2)) {
                DB::rollback();
                return Result::failure()->setType(2)->getResult();
            }
            DB::commit();
            return Result::success()->settype(0)->getResult();
        } else {
            return Result::failure()->settype(3)->getResult();
        }
    }

    /**
     * 所有柜子
     */
    public function allShelf() {
        if ($this->request->isMethod('post')) {
            $model = DB::table('shelves as a');
            $res['count'] = DB::table('shelves as a')
                ->count();
            $res['list'] = $model
                ->leftjoin('doors as b','b.sid','=','a.id')
                ->leftjoin('booksindoor as c','c.DoorID','=','b.code')
                ->groupBy('a.id','a.number','a.type','a.name','a.address','a.lati','a.longi')
                ->select(DB::raw('a.id,a.number,a.type,a.name,a.address,a.lati,a.longi,count(c.id) as count'))
                ->get();
            return Result::success()->setData($res)->setType(0)->getResult();
        } else {
            return Result::failure()->settype(1)->getResult();
        }
    }

    /**
     * 所有图书
     */
    public function allBook() {
        $sid = $this->request->input('sid');
        $p = $this->request->input('p');
        $limit = $this->request->input('limit');
        $res['count'] = DB::table('shelves as a')
            ->where('a.id',$sid)
            ->where('a.type',1)
            ->leftjoin('doors as b','b.sid','=','a.id')
            ->join('booksindoor as c','c.DoorID','=','b.code')
            ->count();
        $res['list'] = DB::table('shelves as a')
            ->where('a.id',$sid)
            ->where('a.type',1)
            ->leftjoin('doors as b','b.sid','=','a.id')
            ->join('booksindoor as c','c.DoorID','=','b.code')
            ->leftjoin('TagInfo as d','d.rUID','=','c.BookEpc')
            ->leftjoin('Items as e','e.BarCode','=','d.Barcode')
            ->leftjoin('circ_marc as f','f.MarcID','=','e.MarcID')
            ->select('e.SerialNo as id','f.ImageUrl','f.Title','f.Author','f.Publisher','e.rent_price')
            ->offset($limit*($p-1))
            ->limit($limit)
            ->get();
        return Result::success()->setData($res)->setType(0)->getResult();
    }

    /**
     * 书柜是否打开
     */
    public function ifOpen() {
        $content = $this->request->input('content');
        $data['number'] = substr($content, 0,6);
        $data['code'] = substr($content, 6,6);
        $data['column'] = substr($content, 12);
        $status = DB::table('doors')->where('code',$data['code'])->value('status');
        if ($status == 2) {
            return Result::success()->setType(0)->setMsg('开门成功')->getResult();
        } else {
            return Result::failure()->setType(1)->setMsg('开门失败')->getResult();
        }
    }


    /**
     * 当前借阅
     */
    public function nowBorrow() {
        if ($this->request->isMethod('post')) {
            $uid = $this->request->input('uid');
            $p = $this->request->input('p');
            $limit = $this->request->input('limit');
            $res = $this->nowBorrows($uid,$p,$limit);
            return $res->getResult();
        } else {
            return Result::failure()->settype(1)->getResult();
        }
    }

    /**
     * 历史借阅
     */
    public function hadBorrow() {
        if ($this->request->isMethod('post')) {
            $uid = $this->request->input('uid');
            $p = $this->request->input('p');
            $limit = $this->request->input('limit');
            $res = $this->hadBorrows($uid,$p,$limit);
            return $res->getResult();
        } else {
            return Result::failure()->settype(1)->getResult();
        }
    }

}
